//
//  MediumFollowReadingTableViewCell.m
//  KidReading
//
//  Created by YangShuai on 2017/5/3.
//  Copyright © 2017年 刘赞黄Telen. All rights reserved.
//

#import "MediumFollowReadingTableViewCell.h"
#import "ConstDefine.h"
@interface MediumFollowReadingTableViewCell ()<TLSoundPlayerDelegate>{
    StatusButton* currentPlayButton;
    NSTimer* _timer;
    NSInteger _timerTime;
    //
    NSInteger _currentScore;
    NSArray* _currentDetailArray;
    //
    BOOL _isHorizontalScreen;
}
//当前Cell文字的录音本地路径(没有本地录音是为nil)
@property(nonatomic,strong)NSString* recordRelativePath;
@property(nonatomic,strong)YSProcessView *processView;
//约束
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *textLeft;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *textTop;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *textRight;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *resultViewTop;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *resultViewWidth;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *playOriWidth;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *recordLeft;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *recordWidth;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *playRecordLeft;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *playOriLeft;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *resultViewRight;

@end

@implementation MediumFollowReadingTableViewCell

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
    //
    if ([[UIApplication sharedApplication] statusBarOrientation] == UIInterfaceOrientationPortrait || [[UIApplication sharedApplication] statusBarOrientation] == UIInterfaceOrientationPortraitUpsideDown) {
        _isHorizontalScreen = NO;
    }else{
        _isHorizontalScreen = YES;
    }
    //
    if (_isHorizontalScreen) {
        _playOriLeft.constant = 180;
        _resultViewRight.constant = 180;
        _recordLeft.constant = 80;
        _playRecordLeft.constant = 80;
    }
    //
    CGFloat ratio_w = [DataProcessing shareSingle].ratio_w;
    if ([DataProcessing shareSingle].deviceType == DevicesTypes_iPhone) {
        _showTextLabel.font = [UIFont systemFontOfSize:30 / ratio_w];
        _textLeft.constant /= ratio_w;
        _textTop.constant /= ratio_w;
        _textRight.constant /= ratio_w;
        _resultViewTop.constant /= ratio_w;
        _resultViewWidth.constant /= ratio_w;
        _playOriWidth.constant /= ratio_w;
        _recordLeft.constant /= ratio_w;
        _recordWidth.constant /= ratio_w;
        _playRecordLeft.constant /= ratio_w;
        _playOriLeft.constant /= ratio_w;
        _resultViewRight.constant /= ratio_w;
    }
    [_playOriBtn addTouchScaleTransitions];
    [_recordBtn addTouchScaleTransitions];
    [_playRecordBtn addTouchScaleTransitions];
    [_playOriBtn addTarget:self action:@selector(tapPlayOri:) forControlEvents:UIControlEventTouchUpInside];
    [_recordBtn addTarget:self action:@selector(tapRecord:) forControlEvents:UIControlEventTouchUpInside];
    [_playRecordBtn addTarget:self action:@selector(tapPlayRecord:) forControlEvents:UIControlEventTouchUpInside];
    //
    _playOriBtn.defaultImageName = @"btn_play_follow.png";
    _playOriBtn.runingImageView = @"btn_stop_follow.png";
    _recordBtn.defaultImageName = @"btn_speaker_follow.png";
    _recordBtn.runingImageView = @"btn_ok_follow.png";
    _playRecordBtn.defaultImageName = @"btn_follow_follow.png";
    _playRecordBtn.runingImageView = @"btn_stop_follow.png";
    //
    _resultView.layer.cornerRadius = 140 / ratio_w / 2;
    _resultView.layer.masksToBounds = YES;
    //
    self.processView = [[YSProcessView alloc] initWithFrame:CGRectMake(0, 0, 140 / ratio_w, 140 / ratio_w)];
    _processView.scaleDivisionsLength = 5 / ratio_w;
    _processView.percent = 0;
    _processView.fontSize = 46 / ratio_w;
    _processView.stopWaveWhenPercentEnd = NO;
    if ([DataProcessing shareSingle].deviceType == DevicesTypes_iPhone) {
        _processView.insideLineMargin = 2;
        _processView.waveMargin = 6;
    }
    [_resultView addSubview: _processView];
}
//
-(void)setLocalResultDict:(NSDictionary *)localResultDict{
    _localResultDict = localResultDict;
    if (localResultDict) {
        NSString* jsonStr = _localResultDict[@"evalInfo"];
        NSDictionary* resultInfoDict = nil;
        if (jsonStr) {
            NSData *jsonData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
            resultInfoDict = [NSJSONSerialization JSONObjectWithData:jsonData
                                                             options:NSJSONReadingMutableContainers
                                                               error:nil];
            NSInteger score = [resultInfoDict[@"score"] integerValue];
            NSArray* detailArray = [self changeResultDictArrayToModelArray:resultInfoDict[@"detail"]];
            [self analysisASRResultToShowDetailWithScore:score DetailArray:detailArray HasAni:NO];
        }
    }
    _playOriBtn.bookId = self.bookId;_recordBtn.bookId = self.bookId;_playRecordBtn.bookId = self.bookId;
    _playOriBtn.pageIndex = self.pageId;_recordBtn.pageIndex = self.pageId;_playRecordBtn.pageIndex = self.pageId;
    _playOriBtn.sentenceId = self.sentenceId;_recordBtn.sentenceId = self.sentenceId;_playRecordBtn.sentenceId = self.sentenceId;
}


-(void)checkRecordExist{
    [[DB_NetFollowReading shareSingle] isContainWordRecordWithBookId:_bookId PageIndex:_pageId SenIndex:_sentenceId IsExist:^(NSString *localFullPath, NSString* relativePath, BOOL isLocalExist, BOOL isSeverExist) {
        self.recordRelativePath = relativePath;
        if (isLocalExist) {
            _playRecordBtn.enabled = YES;
        }else if (!isLocalExist && !isSeverExist){
            _playRecordBtn.enabled = NO;
        }else if (!isLocalExist && isSeverExist){
            _playRecordBtn.enabled = NO;
            //下载音频
            [[DB_NetFollowReading shareSingle] downloadRecordWithRelativePath:relativePath LocalFullPath:localFullPath completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
                [self checkRecordExist];
            }];
        }
    }];
}

//点击播放原音
-(void)tapPlayOri:(StatusButton*)button{
    if (_tapPlayOri) _tapPlayOri(self);
    [self toSuerOneButtonRuning:button];
    if (!button.isRuning) {
        NSString* mp3F = _mp3Path;
        mp3F = [DataProcessing bookPathForBookID:self.bookId subDir:mp3F];
        [[TLSoundPlayer shareSingle] stopAllFiles_andClean];
        [button startRunWithTotleTime:[self getVoiceTimeWithFilePath:mp3F] + 0.5 CurrentTime:0];
        BOOL playSucess = [[TLSoundPlayer shareSingle] rePlayFile:mp3F andDelegate:self];
        if (!playSucess) {
            NSLog(@"播放失败！%@",mp3F);
            [DataProcessing do_Main_quick:^{
                [[TLSoundPlayer shareSingle] rePlayFile:mp3F andDelegate:self];
            }];
        }
    }else{
        [self stopButtonPlay:button];
    }
}

//点击播放录音
-(void)tapPlayRecord:(StatusButton*)button{
    if (_tapPlayRecord) _tapPlayRecord(self);
    [self toSuerOneButtonRuning:button];
    if (!button.isRuning) {
        NSString* localFullPath = [[DB_NetFollowReading shareSingle] getFullPathWithRelativePath:_recordRelativePath];
        [[JRASRManager defaultManager] startPlayRecordWithFullFilePath:localFullPath];
        [button startRunWithTotleTime:[self getVoiceTimeWithFilePath:localFullPath] + 0.5 CurrentTime:0];
    }else{
        [self stopButtonPlay:button];
    }
}

//点击开始录音
-(void)tapRecord:(StatusButton*)button{
    [self toSuerOneButtonRuning:button];
    if (_tapRecord) _tapRecord(self);
    if (!button.isRuning) {
        [[DB_NetFollowReading shareSingle] removeCurrentLocalRecordWithBookId:_bookId PageIndex:_pageId SenIndex:_sentenceId];
        NSDate* date = [NSDate date];
        long long time = [DataProcessing timestampFromNSDate:date];
        self.recordRelativePath = [[JRASRManager defaultManager] startRecordWithBookId:_bookId PageId:_pageId entenceId:_sentenceId RecordTimestamp:time];
        //根据原声时间给定录音时间
        [button startRunWithTotleTime:[self getVoiceTimeWithFilePath:[DataProcessing bookPathForBookID:self.bookId subDir:_mp3Path]] * 2.5 + 1 CurrentTime:0];
        button.timeOutBlock = ^(){
            [self ASRRecordIsInterrupt:NO];
        };
    }else{
        [self ASRRecordIsInterrupt:NO];
    }
}

//完成录音进行评测
-(void)ASRRecordIsInterrupt:(BOOL)isInterrupt{
    [_recordBtn stopRun];
    if (isInterrupt) {
        return;
    }
    [[JRASRManager defaultManager] getDetailString:_ASRText WordArray:_ASRWordArray IsBookEn:_isEnText Completed:^(NSInteger score, NSArray *detailArray) {
        //
        _currentScore = score;
        _currentDetailArray = detailArray;
        
        //根据评分确定显示结果
        [self analysisASRResultToShowDetailWithScore:score DetailArray:detailArray HasAni:YES];
        //存储数据库
        [[DB_NetFollowReading shareSingle] updateASRResultToDBWithDict:[self followReadingResultWithScore:score DetailArray:detailArray] Complete:^{
            //刷新是否有录音页面
            [self checkRecordExist];
            //更新所有录音结果数组
            if (_syncAllResultsArray) {
                _syncAllResultsArray();
            }
        }];
        //将录音上传至upYun
        [[DB_NetFollowReading shareSingle] uploadFollowReadingRecordFileWithSaveKey:self.recordRelativePath EvalResultDict:[self followReadingResultWithScore:score DetailArray:detailArray] Success:^(NSURLResponse *response, id responseData) {
            
        } Failure:^(NSError *error) {
            
        } Progress:nil];
        
    }];
}

//停止播放或者停止录音
-(void)stopButtonPlay:(StatusButton*)button{
    if (button == _playRecordBtn || button == _playOriBtn) {
        [button stopRun];
        [[TLSoundPlayer shareSingle] stopAllFiles_andClean];
    }else if (button == _recordBtn && button.isRuning == YES){
        [self ASRRecordIsInterrupt:YES];
    }
}

//点击按钮确定其他按钮状态
-(void)toSuerOneButtonRuning:(StatusButton*)button{
    NSArray* buttonArray = @[_playOriBtn,_recordBtn,_playRecordBtn];
    for (StatusButton* statusButton in buttonArray) {
        if (statusButton != button && statusButton.isRuning) {
            [self stopButtonPlay:statusButton];
        }
    }
}
//停止当前Cell的button时间
-(void)stopAllRuningButton{
    [self stopButtonPlay:_playRecordBtn];
    [self stopButtonPlay:_playOriBtn];
    [self stopButtonPlay:_recordBtn];
}

//
-(NSInteger)getVoiceTimeWithFilePath:(NSString*)filePath{
    AVAudioPlayer* audioPlayer =  [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:filePath] error:nil];
    return (NSInteger)audioPlayer.duration;
}


//根据分数和详情确定图标和标红字体
-(void)analysisASRResultToShowDetailWithScore:(NSInteger)score DetailArray:(NSArray*)detailArray HasAni:(BOOL)hasAni{
    if (hasAni) {
        [DataProcess do_Main_quick:^{
            if (score < 40) {
                _processView.frontWaterColor = [UIColor colorWithHexString:@"#EDC103"];
                _processView.backWaterColor = _processView.processColor = [UIColor colorWithHexString:@"#FFD623"];
            }else if (score >= 40 && score <= 70){
                _processView.frontWaterColor = [UIColor colorWithHexString:@"#E3A20D"];
                _processView.backWaterColor = _processView.processColor = [UIColor colorWithHexString:@"#FFBA1A"];
            }else{
                _processView.frontWaterColor = [UIColor colorWithHexString:@"#D97215"];
                _processView.backWaterColor = _processView.processColor = [UIColor colorWithHexString:@"#FF8D26"];
            }
            _processView.percent = score / 100.0;
            self.showTextLabel.attributedText = [self changeTextWithFollowReadingResult:detailArray CurrentText:_showTextLabel.text];
            //播放音频
            [self playScoreVoiceWithSocre:score];
        }];
    }else{
        [DataProcess do_Main_quick:^{
            if (score < 40) {
                _processView.frontWaterColor = [UIColor colorWithHexString:@"#EDC103"];
                _processView.backWaterColor = _processView.processColor = [UIColor colorWithHexString:@"#FFD623"];
            }else if (score >= 40 && score <= 70){
                _processView.frontWaterColor = [UIColor colorWithHexString:@"#E3A20D"];
                _processView.backWaterColor = _processView.processColor = [UIColor colorWithHexString:@"#FFBA1A"];
            }else{
                _processView.frontWaterColor = [UIColor colorWithHexString:@"#D97215"];
                _processView.backWaterColor = _processView.processColor = [UIColor colorWithHexString:@"#FF8D26"];
            }
            _processView.noAnimationPercent = score / 100.0;
            self.showTextLabel.attributedText = [self changeTextWithFollowReadingResult:detailArray CurrentText:_showTextLabel.text];
        }];
    }
}

//播放评测音频
-(void)playScoreVoiceWithSocre:(NSInteger)score{
    [[TLSoundPlayer shareSingle] stopAllFiles_andClean];
    int voiceIndex = 1 + arc4random() % (6 - 1 + 1);
    NSString *voiceName = nil;
    if (score < 40) {
        voiceName = [NSString stringWithFormat:@"followReadingVoice.bundle/fail%@",@(voiceIndex)];
    }else if (score >= 40 && score <= 70){
        voiceName = [NSString stringWithFormat:@"followReadingVoice.bundle/pass%@",@(voiceIndex)];
    }else{
        voiceName = [NSString stringWithFormat:@"followReadingVoice.bundle/good%@",@(voiceIndex)];
    }
    NSString *filePath = [[NSBundle mainBundle]pathForResource:voiceName ofType:@"mp3"];
    BOOL playSucess = [[TLSoundPlayer shareSingle] rePlayFile:filePath andDelegate:self];
    if (!playSucess) {
        NSLog(@"播放失败！%@",filePath);
        [DataProcessing do_Main_quick:^{
            [[TLSoundPlayer shareSingle] rePlayFile:filePath andDelegate:self];
        }];
    }
}

//拼凑评测结果Dict(用于存数据库以及上传服务器)
-(NSDictionary*)followReadingResultWithScore:(NSInteger)score DetailArray:(NSArray*)detailArray{
    UserInfo* uinfo = [CacheData shareSingle].getUserLoginInfo;
    NSArray* resultDictArray = [self changeResultModelArrayToDictArray:detailArray];
    NSDictionary* resultDict = @{@"score":@(score),@"detail":resultDictArray};
    NSData* Data = [NSJSONSerialization dataWithJSONObject:resultDict options:NSJSONWritingPrettyPrinted error:nil];
    NSString* jsondate = @"";
    if (Data) {
        jsondate = [[NSString alloc] initWithBytes:Data.bytes length:Data.length encoding:NSUTF8StringEncoding];
    }
    NSMutableDictionary* dict = [NSMutableDictionary new];
    [dict setValue:@(uinfo.uid) forKey:@"userId"];
    [dict setValue:@(_bookId) forKey:@"bookId"];
    [dict setValue:@(_pageId) forKey:@"pageIndex"];
    [dict setValue:@(_sentenceId) forKey:@"senIndex"];
    [dict setValue:_showTextLabel.text forKey:@"sentence"];
    [dict setValue:self.recordRelativePath forKey:@"radioSrc"];
    [dict setValue:@(1) forKey:@"evalFlag"];
    [dict setValue:jsondate forKey:@"evalInfo"];
    return dict;
}



//将返回的评测结果转化为字典数组
-(NSArray*)changeResultModelArrayToDictArray:(NSArray*)modelArray{
    NSMutableArray* dictArray = [NSMutableArray new];
    for (ASRWordScore* resultModel in modelArray) {
        NSMutableDictionary* resultDict = resultModel.JRMJ_keyValues;
        [resultDict removeObjectForKey:@"mBeginTime"];
        [resultDict removeObjectForKey:@"mReason"];
        [resultDict removeObjectForKey:@"mEndTime"];
        [dictArray addObject:resultDict];
    }
    return dictArray;
}
//将评测结果字典转化为对象数组
-(NSArray*)changeResultDictArrayToModelArray:(NSArray*)dictArray{
    NSMutableArray* modelArray = [NSMutableArray new];
    for (NSDictionary* resultDict in dictArray) {
        ASRWordScore* resultModel = [ASRWordScore JRMJ_objectWithKeyValues:resultDict];
        [modelArray addObject:resultModel];
    }
    return modelArray;
}

//属性字符串处理
-(NSMutableAttributedString*)changeTextWithFollowReadingResult:(NSArray*)followReadingResult CurrentText:(NSString*)currentText{
    NSMutableAttributedString *AttributedStr = [[NSMutableAttributedString alloc]initWithString:currentText];
    for (int i = 0; i < followReadingResult.count; i ++) {
        ASRWordScore* resultModel = followReadingResult[i];
        NSRange textRange = NSMakeRange(0, 0);
        if (i < self.rangeArray.count) {
            textRange = [self.rangeArray[i] rangeValue];
        }
        if (resultModel.mScore < 40) {
            [AttributedStr addAttribute:NSForegroundColorAttributeName
                                  value:[UIColor redColor]
                                  range:textRange];
        }else if(resultModel.mScore >= 40 && resultModel.mScore <= 70){
            [AttributedStr addAttribute:NSForegroundColorAttributeName
                                  value:[UIColor colorWithHexString:@"#FFBA1A"]
                                  range:textRange];
        }else{
            [AttributedStr addAttribute:NSForegroundColorAttributeName
                                  value:[UIColor blackColor]
                                  range:textRange];
        }
    }
    return AttributedStr;
}

//判断一个字符是否为英文字母
-(BOOL)charIsEnWord:(unichar)word{
    if (((int)word >= 'a' && (int)word <= 'z') || ((int)word >= 'A' && (int)word <= 'Z')) {
        return YES;
    }else{
        return NO;
    }
}

-(void)cleanCellInfo{
    self.showTextLabel.text = nil;
    self.localResultDict = nil;
    [self.playOriBtn stopRunTimerGoOn];
    [self.recordBtn stopRunTimerGoOn];
    [self.playRecordBtn stopRunTimerGoOn];
}

#pragma mark - TLSoundDelegate
- (void)tlSoundPlayerDidFinishPlayingFile:(NSString*)fileFullPath player:(AVAudioPlayer *)player{
    [[TLSoundPlayer shareSingle] stopFilePlay_andClean:fileFullPath];
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];
    
    // Configure the view for the selected state
}

@end
